package emulator.GUI;

import java.awt.Rectangle;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.prefs.Preferences;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class PersistentFrame extends JFrame implements WindowListener {

	/**
	 * Persistent preference storage
	 */
	private Preferences cfg;
	private String pref_prefix;

	/**
	  * The default window geometry
	  */
	public static final Rectangle GEOMETRY = new Rectangle(0,0,640,480);
	
	public static Rectangle getDefaultGeometry() { return GEOMETRY; }
	  
	public PersistentFrame(String name)
	{	
		super(name);
		pref_prefix = name+".";
		
		// Load preferences
	    cfg = Preferences.userNodeForPackage(this.getClass());
	    
	    // For saving settings upon window closing
	    addWindowListener(this);
	    
	    FrameRegistry.getInstance().registerFrame(this);
	}

	public void restorePosition() {
		// Restore window geometry
	    Rectangle bounds = new Rectangle();
	    bounds.x = cfg.getInt(pref_prefix+"window.x", getDefaultGeometry().x);
	    bounds.y = cfg.getInt(pref_prefix+"window.y", getDefaultGeometry().y);
	    bounds.width = cfg.getInt(pref_prefix+"window.width", getDefaultGeometry().width);
	    bounds.height = cfg.getInt(pref_prefix+"window.height", getDefaultGeometry().height);
	    setBounds(bounds); // Do not use pack()!
	}
	
	@Override
	public void windowActivated(WindowEvent arg0) {}

	@Override
	public void windowClosed(WindowEvent arg0) {}

	@Override
	public void windowClosing(WindowEvent arg0)
	{	// Save Settings
	    savePosition();		
	}

	public void savePosition() {
		Rectangle bounds = getBounds();
	    cfg.putInt(pref_prefix+"window.x", bounds.x);
	    cfg.putInt(pref_prefix+"window.y", bounds.y);
	    cfg.putInt(pref_prefix+"window.width", bounds.width); 
	    cfg.putInt(pref_prefix+"window.height", bounds.height);
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {}

	@Override
	public void windowDeiconified(WindowEvent arg0) {}

	@Override
	public void windowIconified(WindowEvent arg0) {}

	@Override
	public void windowOpened(WindowEvent arg0) {}

}
